<template>
    <view>
        <view style="background-color: white">
            <!-- 基础表单校验 -->
            <up-form :model="form" :rules="rules" label-width="90px" ref="formRef">
                <view class="form_part">
                    <up-form-item v-if="form.text == '起运'" label="货运数量" prop="goodsCount" border-bottom>
                        <up-input placeholder="请输入货运数量" border="none" v-model="form.goodsCount"></up-input>
                    </up-form-item>
                    <up-form-item v-if="formStatus.shippedNumEnabled" label="实发量" border-bottom>
                        <up-input placeholder="请输入实发量" border="none" v-model="form.shippedNum"></up-input>
                    </up-form-item>
                    <up-form-item label="实卸量" border-bottom v-if="formStatus.receiptedNumEnabled">
                        <up-input placeholder="请输入实卸量" border="none" v-model="form.receiptedNum"></up-input>
                    </up-form-item>
                    <up-form-item label="回单图片" border-bottom v-if="formStatus.relevantPicEnabled || form.relevantPic">
                        <div>
                            <up-upload accept="image" :fileList="imageUrls" @afterRead="afterRead" @delete="deletePic"
                                deletable multiple :maxCount="3" :previewFullImage="true"></up-upload>
                        </div>
                    </up-form-item>
                </view>
            </up-form>
        </view>
        <view class="form_button">
            <up-button type="primary" @click="WithConfirm">提交</up-button>
            <up-button v-if="form.text == '起运'" style="margin-top: 5px" type="primary"
                @click="CancelWaybill">取消运单</up-button>
        </view>
    </view>
    <up-toast ref="uToastRef"></up-toast>
</template>

<script lang="ts" setup>
import {
    onLoad
} from "@dcloudio/uni-app"
import {
    ref,
    reactive
} from "vue"
import {
    getImage,
    uploadFile
} from '@/api/file'
import {
    DepartureWaybill,
    ReachWaybill,
    receiptWaybill,
    CancelWaybillShip,
    updateReceiptWaybill
} from '@/api/driver'

/* 数据 */
const uToastRef = ref<any>(null)
const formRef = ref<UniFormRef | null>(null)
const form = reactive({
    id: '',
    billId: '',
    shippedNum: '',
    text: '',
    receiptedNum: undefined,
    vehicleId: '',
    relevantPic: '',
    banId: '',
    goodsCount: '',
    relevantPicIds: [] as string[] // 存储图片ID数组
})
const rules = reactive({
    'goodsCount': {
        type: 'number',
        required: true,
        message: '请输入货运数量',
        trigger: ['blur', 'change']
    }
})
const imageUrls = reactive<Array<{ url: string }>>([]) // 存储上传的图片URL
// 新增状态控制变量
const formStatus = reactive({
    shippedNumEnabled: false,
    receiptedNumEnabled: false,
    relevantPicEnabled: false
})
// 上传回单还是修改回单
const flag = ref(0)


/* 函数 */
interface uploadCallbackParams {
    index: number,
    file: any,
    name: string
}
// 删除图片
const deletePic = (e: uploadCallbackParams) => {
    imageUrls.splice(e.index, 1)
    form.relevantPicIds.splice(e.index, 1)
}
// 选择图片后回调
const afterRead = async (e: uploadCallbackParams) => {
    if (e.file.length > 3) {
        uToastRef.value.show({
            position: "top",
            message: '最多只能上传三张图片',
            type: 'warning'
        })
        return
    }
    uToastRef.value.show({
        message: '图片上传中',
        type: 'loading',
        duration: -1
    })
    const fileUrl = e.file.map((item: any) => item.url)
    try {
        let resList = await Promise.all(fileUrl.map((url: string) => {
            return uploadFile(url, {
                licenseType: -1,
                secondFilePath: `waybill/relevantPic/${form.billId}`
            })
        }))
        uToastRef.value.hide()
        form.relevantPicIds.push(...resList.map((item: any) => item.data.fileId))
        imageUrls.push(...fileUrl.map((item: string) => {
            return {
                url: item
            }
        }))
    } catch (err: any) {
        uToastRef.value.hide()
        uToastRef.value.show({
            position: "top",
            message: '上传失败，' + err.message,
            type: 'error'
        })
    }

}
// 查看打卡方案
const getWaybillClock = (data: any) => {
    // 直接根据接口返回的值决定是否显示对应字段
    formStatus.shippedNumEnabled = data.shippedNum == '1'
    formStatus.receiptedNumEnabled = data.receiptedNum == '1'
    formStatus.relevantPicEnabled = data.relevantPic == '1'
}
// 查看照片 - 支持多图
const getImages = (type: string, name: string) => {
    if (name !== 'relevantPic') return

    // 清空现有数据
    imageUrls.length = 0
    form.relevantPicIds = []

    // 如果没有图片ID，直接返回
    if (!type || type.trim() === '') return

    // 分割ID字符串为数组
    const ids = type.split(',').map(id => id.trim()).filter(id => id)
    console.log(ids)
    // 依次获取每张图片
    const promises = ids.map(async (id) => {
        return await getImage(id).then(res => {
            if (res.code === 200) {
                return {
                    id: id,
                    url: res.data
                }
            }
            return null
        }).catch(err => {
            console.error(`获取图片 ${id} 失败:`, err)
            return null
        })
    })

    // 等待所有图片获取完成
    Promise.all(promises).then(results => {
        const validResults = results.filter(item => item !== null)

        // 更新数据
        form.relevantPicIds = validResults.map(item => item.id)
        imageUrls.push(...validResults.map((item: any) => {
            return {
                url: item.url
            }
        }))

        // 确保form.relevantPic是最新的ID字符串
        form.relevantPic = form.relevantPicIds.join(',')
    })
}
// 提交
const WithConfirm = async () => {
    let valid = await formRef.value?.validate()
    if (valid) {
        let params = {
            ...form,
            relevantPic: form.relevantPicIds.join(',')
        }
        let regex = /^\d+(\.\d+)?$/
        if (params.goodsCount) {
            if (!regex.test(params.goodsCount)) {
                uToastRef.value.show({
                    position: "top",
                    message: '货运数量只能为数字加小数点',
                    type: 'warning'
                })
                return
            }
        }
        if (params.shippedNum) {
            if (!regex.test(params.shippedNum)) {
                uToastRef.value.show({
                    position: "top",
                    message: '实发量只能为数字加小数点',
                    type: 'warning'
                })
                return
            }
        }
        if (params.receiptedNum) {
            if (!regex.test(params.receiptedNum)) {
                uToastRef.value.show({
                    position: "top",
                    message: '实卸量只能为数字加小数点',
                    type: 'warning'
                })
                return
            }
        }
        if (form.text == '起运') {
            uToastRef.value.show({
                message: '起运中，请稍等...',
                type: 'loading',
                duration: -1
            })
            let res = await DepartureWaybill(params)
            uToastRef.value.hide()
            if (res.success) {
                uToastRef.value.show({
                    position: "top",
                    message: '配货单已起运',
                    type: 'success',
                    complete() {
                        uni.navigateBack()
                    }
                })
            }
        } else if (form.text == '到达') {
            uToastRef.value.show({
                message: '请稍等...',
                type: 'loading',
                duration: -1
            })
            let res = await ReachWaybill(params)
            uToastRef.value.hide()
            if (res.success) {
                uToastRef.value.show({
                    position: "top",
                    message: '配货单已到达',
                    type: 'success',
                    complete() {
                        uni.navigateBack()
                    }
                })
            }
        } else if (form.text == '上传回单') {
            uToastRef.value.show({
                message: '请稍等...',
                type: 'loading',
                duration: -1
            })
            let fn = null
            let params = {
                ...form,
                relevantPic: form.relevantPicIds.join(',')
            }
            if (flag.value == 0) {
                fn = receiptWaybill
            } else {
                fn = updateReceiptWaybill
            }
            let res = await fn(params)
            uToastRef.value.hide()
            if (res.success) {
                uToastRef.value.show({
                    position: "top",
                    message: '配货单已上传回单',
                    type: 'success',
                    complete() {
                        uni.navigateBack()
                    }
                })
            }
        }
    }
}
// 取消订单
const CancelWaybill = async () => {
    // 先弹出确认提示框
    uni.showModal({
        title: '提示',
        content: '确定要取消该订单吗？',
        success: async (res) => {
            if (res.confirm) {
                // 用户点击了确定
                let params = {
                    id: form.id
                }
                console.log(params)
                let cancelRes = await CancelWaybillShip(params)
                if (cancelRes.success) {
                    uToastRef.value.show({
                        position: "top",
                        message: '您已取消该订单',
                        type: 'warning',
                        complete() {
                            uni.navigateBack()
                        }
                    })
                }
            }
        }
    })
}



/* 钩子 */
onLoad((options: any) => {
    form.id = JSON.parse(options.item).id
    form.billId = JSON.parse(options.item).billId
    form.vehicleId = JSON.parse(options.item).vehicleId
    form.banId = JSON.parse(options.item).banId
    if (JSON.parse(options.item).goodsCount) {
        let goodsCount = JSON.parse(options.item).goodsCount
        form.goodsCount = goodsCount
    }
    if (JSON.parse(options.item).shippedNum != 0) {
        form.shippedNum = JSON.parse(options.item).shippedNum
    }
    if (JSON.parse(options.item).receiptedNum != 0) {
        form.receiptedNum = JSON.parse(options.item).receiptedNum
    }
    if (JSON.parse(options.item).relevantPic) {
        form.relevantPic = JSON.parse(options.item).relevantPic
        getImages(JSON.parse(options.item).relevantPic, 'relevantPic')
    }
    form.text = options.text
    flag.value = options.flag
    getWaybillClock(JSON.parse(options.dataList))
})
</script>

<style lang="scss" scoped>
.images {
    width: 150px;
    height: 150px;
}

.form_part {
    background-color: #fff;
    padding: 10px;
    box-sizing: border-box;
    margin-bottom: 10px;
}

.form_button {
    margin-left: 5%;
    width: 90%;
}

.image-container {
    display: flex;
    flex-wrap: wrap;
}

.image-item {
    position: relative;
}

.delete-btn {
    position: absolute;
    top: 0;
    right: 0;
    background-color: rgba(255, 0, 0, 0.5);
    color: white;
    width: 32px;
    height: 40px;
}

.delete-btn:hover {
    background-color: red;
}

/* 添加禁用状态的样式 */
.uv-input--disabled {
    background-color: #f5f5f5;
    color: #999;
}
</style>